package com.hx.vending.controller;

import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.vending.annotation.*;
import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.*;
import com.hx.vending.mqtt.RunnerSendMqtt;
import com.hx.vending.service.*;
import com.hx.vending.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.ibatis.annotations.Param;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Created by Administrator on 2018/11/26.
 */
@Controller
@RequestMapping("/equipment")
public class EquipmentController {

    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IFieldService fieldService;
    @Autowired
    private ITransferService transferService;
    @Autowired
    private ITrailsService trailsService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /*
    * 设备查询
    * */
    @RequestMapping(value = "/getEquipmentByCondition", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg getEquipment(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                            @CurrentFieldId Integer[] integers, @CurrentUserId Integer userId,
                            String content, String state, Integer fieldId){
       List<Equipment> list = new ArrayList<>();
        Equipment equipment = new Equipment();
        //用户id
        if(ToolUtil.isNotEmpty(userId)){
            equipment.setEquipmentUserId(userId);
        }else{
            return Msg.fail().add("va_msg", "未找到对应用户");
        }
        //查询条件 设备id
        if(ToolUtil.isNotEmpty(content)){
            equipment.setEquipmentId(content);
        }
        //设备状态
        if(ToolUtil.isNotEmpty(state)){
            //离线
            if (state.equals("2")) {

                equipment.setEquipmentState("2");

            }else if(state.equals("1")){
                equipment.setEquipmentState("1");
            }
        }
        //场地id
        List<EquipmentList>  equipmentLists = new ArrayList<>();
        if(ToolUtil.isNotEmpty(fieldId)){
            if(fieldId != 0){
                EquipmentList equipmentList = new EquipmentList();
                Field field1 = new Field();
                field1.setFieldId(fieldId);
                Field f = fieldService.selectByPrimary(field1);
                equipmentList.setFieldId(f.getFieldId());
                equipmentList.setFieldName(f.getFieldName());
                equipmentList.setFieldAddress(f.getFieldAddress());

                equipment.setEquipmentFieldId(fieldId);
                list = equipmentService.selectByExample(equipment);
                if(list.size()>0){
                    List<EquipmentModel> equipmentModels = new ArrayList<>();
                    for(Equipment e:list){
                        EquipmentModel equipmentModel = new EquipmentModel();
                        equipmentModel.setEquipmentId(e.getEquipmentId());
                        equipmentModel.setEquipmentRemarks(e.getEquipmentRemarks());
                        equipmentModel.setEquipmentNumber(e.getEquipmentNumber());
                        equipmentModel.setEquipmentState(e.getEquipmentState());
                        equipmentModel.setEquipmentSignal(e.getEquipmentSignal());
                        equipmentModel.setEquipmentType(e.getEquipmentType());
                        equipmentModel.setEquipmentScreen(e.getEquipmentScreen());
                        equipmentModel.setEquipmentSignalType(e.getEquipmentSignalType());
                        if(ToolUtil.isNotEmpty(e.getEquipmentModelId())){
                            equipmentModel.setEquipmentModelId(e.getEquipmentModelId());
                            Model model =  equipmentService.selectModelById(e.getEquipmentModelId());
                            if(ToolUtil.isNotEmpty(model)){
                                equipmentModel.setModelName(model.getModelName());
                            }
                        }
                        equipmentModels.add(equipmentModel);

                    }
                    //设备总数
                    equipmentList.setNum(list.size());
                    //设备离线数量
                    for(Equipment e:list){
                        if(e.getEquipmentState().equals("2")){
                            equipmentList.setUnlineNum(equipmentList.getUnlineNum()+1);
                        }
                    }

                    equipmentList.setEquipmentList(equipmentModels);

                    equipmentLists.add(equipmentList);
                }
            }else{
               /* Field field1 = new Field();
                field1.setFieldUserId(userId);*/
                //所有场地
                List<Field> fieldList = fieldService.selectFieldById(integers);
                for(Field f:fieldList){
                    List<EquipmentModel> equipmentModels = new ArrayList<>();
                    EquipmentList equipmentList = new EquipmentList();
                    equipmentList.setFieldId(f.getFieldId());
                    equipmentList.setFieldName(f.getFieldName());
                    equipmentList.setFieldAddress(f.getFieldAddress());
                    equipment.setEquipmentFieldId(f.getFieldId());
                    list = equipmentService.selectByExample(equipment);
                    if(list.size()>0){
                        for(Equipment e:list){
                            EquipmentModel equipmentModel = new EquipmentModel();
                            equipmentModel.setEquipmentId(e.getEquipmentId());
                            equipmentModel.setEquipmentRemarks(e.getEquipmentRemarks());
                            equipmentModel.setEquipmentNumber(e.getEquipmentNumber());
                            equipmentModel.setEquipmentState(e.getEquipmentState());
                            equipmentModel.setEquipmentSignal(e.getEquipmentSignal());
                            equipmentModel.setEquipmentType(e.getEquipmentType());
                            equipmentModel.setEquipmentScreen(e.getEquipmentScreen());
                            equipmentModel.setEquipmentSignalType(e.getEquipmentSignalType());
                            if(ToolUtil.isNotEmpty(e.getEquipmentModelId())){
                                equipmentModel.setEquipmentModelId(e.getEquipmentModelId());
                                Model model =  equipmentService.selectModelById(e.getEquipmentModelId());
                                if(ToolUtil.isNotEmpty(model)){
                                    equipmentModel.setModelName(model.getModelName());
                                }

                            }
                            equipmentModels.add(equipmentModel);

                        }
                            //设备总数
                            equipmentList.setNum(list.size());
                            //设备离线数量
                            for(Equipment e:list){
                                if(e.getEquipmentState().equals("2")){
                                    equipmentList.setUnlineNum(equipmentList.getUnlineNum()+1);
                                }
                            }
                            equipmentList.setEquipmentList(equipmentModels);
                            equipmentLists.add(equipmentList);
                    }
                }

            }
        }
        Paging paging = Paging.pagination(equipmentLists.size(),pageSize,pageNum);
        int fromIndex = paging.getQueryIndex();
        int toIndex = 0;
        if (fromIndex + paging.getPageSize() >= equipmentLists.size()){
            toIndex = equipmentLists.size();
        }else {
            toIndex = fromIndex +  paging.getPageSize();
        }
        if (fromIndex > toIndex){

            return Msg.success().add("pageInfo",Collections.EMPTY_LIST);
        }
        return Msg.success().add("pageInfo", equipmentLists.subList(fromIndex,toIndex));
    }


    /**
     * 根据ID查询
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getEquipmentById/{equipmentId}", method = RequestMethod.GET)
    @ResponseBody
    @Authorization
    public Msg getEquipmentById(@PathVariable("equipmentId") String equipmentId) {
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment eq = equipmentService.selectByPrimary(equipment);
        if (eq != null) {
            return Msg.success().add("equipment", eq);
        } else {
            return Msg.fail().add("va_msg", "未找到该设备信息");
        }
    }
    /*
    *查询商家设备离线多少，在线多少
    * */
    @RequestMapping("/getEquipmentByUserState")
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg getEquipmentByUserState(@CurrentFieldId Integer[] integers){
        Integer onlinesum = 0;
        Integer offlinesum = 0;
        Integer sum = 0;
        EquipmentState equipmentState = new EquipmentState();

        List<Equipment> equipmentList = equipmentService.selectByFieldIds(integers);
        if(CollectionUtils.isNotEmpty(equipmentList)){
            for(Equipment e:equipmentList){
                if(e.getEquipmentState().equals("1")){
                    ++onlinesum;
                }else if(e.getEquipmentState().equals("2")){
                    ++offlinesum;
                }
            }
            sum += equipmentList.size();
        }
        equipmentState.setOffLineSum(offlinesum);
        equipmentState.setOnLineSum(onlinesum);
        equipmentState.setSum(sum);
        return Msg.success().add("equipmentState",equipmentState);
    }

    /*
    * 检查设备是否已注册
    * */
    @RequestMapping(value = "/checkEquipmentId",method = RequestMethod.GET)
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg checkEquipmentId(String equipmentId ,@CurrentFieldId Integer[] integers){
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment equipment1 = equipmentService.selectByPrimary(equipment);
        EquipmentByFieldCheckNumber byFieldCheckNumber = new EquipmentByFieldCheckNumber();
        if(ToolUtil.isNotEmpty(equipment1) && ToolUtil.isNotEmpty(equipment1.getEquipmentUserId())){
                if(ToolUtil.isNotEmpty(equipment1.getEquipmentFieldId())){
                    byFieldCheckNumber.setEquipmentId(equipment1.getEquipmentId());
                    byFieldCheckNumber.setEquipmentNumber(equipment1.getEquipmentNumber());
                    byFieldCheckNumber.setEquipmentState(equipment1.getEquipmentState());
                    byFieldCheckNumber.setEquipmentModelId(equipment1.getEquipmentModelId());
                    Model m = new Model();
                    m.setModelId(equipment1.getEquipmentModelId());
                    Model model = equipmentService.selectModelById(equipment1.getEquipmentModelId());
                    if(ToolUtil.isNotEmpty(model)){
                        byFieldCheckNumber.setEquipmentModelName(model.getModelName());
                    }
                    Field fl = new Field();
                    fl.setFieldId(equipment1.getEquipmentFieldId());// 3 3h 4 1h 12 drf
                    Field flll = fieldService.selectByPrimary(fl);
                    byFieldCheckNumber.setEquipmentFieldName(flll.getFieldName());
                    byFieldCheckNumber.setEquipmentFieldId(flll.getFieldId());

                }

                List<Field> list = fieldService.selectFieldById(integers);
                List<FiledCheckNumber> checkNumbers = new ArrayList<FiledCheckNumber>();
                for(int i = 0; i< list.size();i++){
                    FiledCheckNumber checkNumber = new FiledCheckNumber();
                    checkNumber.setFieldId(list.get(i).getFieldId());
                    checkNumber.setFieldName(list.get(i).getFieldName());
                    checkNumber.setFieldAddress(list.get(i).getFieldAddress());
                    Equipment eqi = new Equipment();
                    eqi.setEquipmentFieldId(list.get(i).getFieldId());
                    List<Equipment> equipments = equipmentService.selectByExample(eqi);
                    Integer[] a = new Integer[equipments.size()];

                    for (int j = 0; j < equipments.size(); j++) {
                        a[j] = equipments.get(j).getEquipmentNumber();
                    }

                    checkNumber.setNumber(a);
                    checkNumbers.add(checkNumber);
                }
                byFieldCheckNumber.setList(checkNumbers);
                // 没有设备，要拿到投放地址列表
                if(ToolUtil.isEmpty(equipment1)){
                    return Msg.success().add("byFieldCheckNumber", byFieldCheckNumber).add("address", "");
                }
                // 场地id
                Integer equipmentFieldId = equipment1.getEquipmentFieldId();

                if (ToolUtil.isEmpty(equipmentFieldId)) {
                    return Msg.success().add("byFieldCheckNumber", byFieldCheckNumber).add("address", "");
                }
                Field field1 = new Field();
                field1.setFieldId(equipmentFieldId);
                //查询场地地址
                field1 = fieldService.selectByPrimary(field1);
                if (ToolUtil.isEmpty(field1)) {
                    return Msg.fail().add("msg", "根据设备的场地id查询场地信息为空");
                }
                    return Msg.success().add("byFieldCheckNumber", byFieldCheckNumber).add("address", field1.getFieldAddress());
            }else{

                List<Field> list = fieldService.selectFieldById(integers);
                List<FiledCheckNumber> checkNumbers = new ArrayList<FiledCheckNumber>();
                for(int i = 0;i < list.size();i++){
                FiledCheckNumber checkNumber = new FiledCheckNumber();
                checkNumber.setFieldId(list.get(i).getFieldId());
                checkNumber.setFieldName(list.get(i).getFieldName());
                checkNumber.setFieldAddress(list.get(i).getFieldAddress());
                Equipment eqi = new Equipment();
                eqi.setEquipmentFieldId(list.get(i).getFieldId());
                List<Equipment> equipments = equipmentService.selectByExample(eqi);
                Integer[] a = new Integer[equipments.size()];
                if (equipments.size() > 0) {
                    for (int j = 0; j < equipments.size(); j++) {
                        a[j] = equipments.get(j).getEquipmentNumber();

                    }
                }
                checkNumber.setNumber(a);

                checkNumbers.add(checkNumber);
            }
            Msg msg = new Msg();
            msg.setCode(202);
            msg.setMsg("成功");
            return msg.add("checkNumbers", checkNumbers);
        }
    }
    /*
    * 设备注册
    * */
    @RequestMapping(value="/saveEquipment")
    @ResponseBody
    @Authorization
    public Msg saveEquipment(@RequestBody Equipment equipment,@CurrentUserId Integer userId, BindingResult result){
            if(result.hasErrors()){
            // 校验失败，应该返回失败，在模态框中显示校验失败的错误信息
            Map<String, Object> map = new HashMap<String, Object>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        }else{
             Equipment e1 = new Equipment();
             e1.setEquipmentId(equipment.getEquipmentId());
             Equipment e = equipmentService.selectByPrimary(e1);
             if(ToolUtil.isNotEmpty(e)){
                 if(ToolUtil.isNotEmpty(e.getEquipmentUserId())){
                     equipment.setEquipmentUserId(null);
                     equipment.setEquipmentFieldId(null);
                     equipment.setEquipmentNumber(null);
                     equipment.setEquipmentRemarks(null);
                     int result1 = equipmentService.updateByEqipment(equipment);
                     Field field = this.selectByFieldId(e.getEquipmentFieldId());
                     String beforeAddress = field.getFieldName() +"("+ field.getFieldAddress()+") "+e.getEquipmentNumber()+"号机";
                     if(result1 != 0){
                         Transfer transfer = new Transfer();
                         transfer.setTransferEquipmentId(equipment.getEquipmentId());
                         transfer.setTransferUserId(e.getEquipmentUserId());
                         transfer.setTransferBeforeAddress(beforeAddress);
                         transfer.setTransferTime(ToolUtil.currentTime());
                         transfer.setTransferType("3");
                         transfer.setTransferFieldId(field.getFieldId());
                         transfer.setTransferEquipmentType(e.getEquipmentType());
                         transferService.insertSelective(transfer);
                     }
                 }
                 //根据设备id判断数据库是否存在该设备，如果存在则更新。不存在则插入
                 equipment.setEquipmentCreateTime(ToolUtil.currentTime());
                 equipment.setEquipmentUserId(userId);
                 int result1 = equipmentService.updateByPrimaryKeySelective(equipment);
                 if (result1 != 0) {
                     Equipment equipment1 = equipmentService.selectByPrimary(equipment);
                     Field fi = new Field();
                     fi.setFieldId(equipment1.getEquipmentFieldId());
                     Field fl = fieldService.selectByPrimary(fi);
                     Transfer transfer = new Transfer();
                     transfer.setTransferEquipmentId(equipment1.getEquipmentId());
                     transfer.setTransferBeforeAddress(fl.getFieldName() +"("+ fl.getFieldAddress()+") "+equipment1.getEquipmentNumber()+"号机");
                     transfer.setTransferTime(equipment1.getEquipmentCreateTime());
                     transfer.setTransferType("1");
                     transfer.setTransferFieldId(fl.getFieldId());
                     transfer.setTransferUserId(equipment1.getEquipmentUserId());
                     transfer.setTransferEquipmentType(equipment1.getEquipmentType());
                     transferService.insertSelective(transfer);
                     return Msg.success();
                 } else {
                     return Msg.fail();
                 }
             }else{
                 return Msg.fail().add("msg","找不到该设备，请联系厂商");
             }
        }
    }

    /*
    * 转移设备
    * */
    @ResponseBody
    @RequestMapping(value = "/updateEquipment", method = RequestMethod.POST)
    @Authorization
    public Msg updateEquipment(@RequestBody Equipment equipment,@CurrentUserId Integer userId){
        Equipment equipment1 = new Equipment();
        equipment1.setEquipmentId(equipment.getEquipmentId());
        Equipment e = equipmentService.selectByPrimary(equipment1);
        Field f = new Field();
        f.setFieldId(e.getEquipmentFieldId());
        Field field = fieldService.selectByPrimary(f);
        String beforAddress = field.getFieldName() +"("+ field.getFieldAddress() +") "+e.getEquipmentNumber()+"号机";

        int result = equipmentService.updateByPrimaryKeySelective(equipment);
        if(result != 0){
            Transfer transfer = new Transfer();
            transfer.setTransferEquipmentId(equipment.getEquipmentId());
            //转出场地
            transfer.setTransferBeforeAddress(beforAddress);
            transfer.setTransferTime(ToolUtil.currentTime());
            transfer.setTransferType("2");
            transfer.setTransferFieldId(field.getFieldId());
            Field field2 = new Field();
            field2.setFieldId(equipment.getEquipmentFieldId());
            Field field3 = fieldService.selectByPrimary(field2);
            //转入场地
            transfer.setTransferEquipmentFieldAddress(field3.getFieldName() +"("+ field3.getFieldAddress() +") "+ equipment.getEquipmentNumber() +"号机");
            transfer.setTransferUserId(userId);
            transfer.setTransferEquipmentType(e.getEquipmentType());
            transferService.insertSelective(transfer);
            return Msg.success();
        }else{
            return Msg.fail();
        }
    }

    /*
    * 解绑
    * */
    @ResponseBody
    @RequestMapping(value = "/deleteEquipment/{ids}", method = RequestMethod.DELETE)
    @Authorization
    public Msg deleteEquipment(@PathVariable("ids") String ids,@CurrentUserId Integer userId){
        try{
            String[] split = ids.split("-");
            for(String eqId:split){
                Equipment e = this.selectByEquipmentId(eqId);
                if(ToolUtil.isNotEmpty(e) && e.getEquipmentUserId().equals(userId)){
                    Integer fieldId = e.getEquipmentFieldId();
                    Equipment equipment = new Equipment();
                    equipment.setEquipmentId(e.getEquipmentId());
                    equipment.setEquipmentUserId(null);
                    equipment.setEquipmentFieldId(null);
                    equipment.setEquipmentNumber(null);
                    equipment.setEquipmentRemarks(null);
                    equipment.setEquipmentModelId(null);
                    equipment.setEquipmentPicture(null);
                    equipment.setEquipmentVideo(null);
                /*int i = riseService.deleteRiseByEquipmentId(eqId);
                int j = trailsService.deleteByEquipmentId(eqId);*/
                    Trails t = new Trails();
                    t.setTrailsEquipmentId(eqId);
                    List<Trails> trailsList = trailsService.selectByExample(t);
                    for(Trails trails:trailsList){
                        trails.setTrailsId(trails.getTrailsId());
                        trails.setTrailsGoodsStock(0);
                        trails.setTrailsGoodsId(null);
                        trailsService.updateByTrails(trails);
                    }
                    int result = equipmentService.updateByEqipment(equipment);

                    Field field = this.selectByFieldId(fieldId);
                    String beforeAddress = field.getFieldName() +"("+field.getFieldAddress()+") "+e.getEquipmentNumber()+"号机";
                    if(result != 0){
                        Transfer transfer = new Transfer();
                        transfer.setTransferEquipmentId(e.getEquipmentId());
                        transfer.setTransferBeforeAddress(beforeAddress);
                        transfer.setTransferUserId(userId);
                        transfer.setTransferTime(ToolUtil.currentTime());
                        transfer.setTransferType("3");
                        transfer.setTransferFieldId(field.getFieldId());
                        transfer.setTransferEquipmentType(e.getEquipmentType());
                        transferService.insertSelective(transfer);
                    }
                    //删除线下订单表
                    //删除线上订单表
                }
            }
            return Msg.success();
        }catch(Exception e){
            return Msg.fail();
        }
    }

    /**
     * 解绑（后台）
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteEquipmentBack/{ids}", method = RequestMethod.DELETE)
    public Msg deleteEquipmentBack(@PathVariable("ids") String ids){

        try{
            String[] split = ids.split("-");
            for(String eqId:split){
                Equipment e = this.selectByEquipmentId(eqId);
                if(ToolUtil.isNotEmpty(e)){
                    Integer fieldId = e.getEquipmentFieldId();
                    Equipment equipment = new Equipment();
                    equipment.setEquipmentId(e.getEquipmentId());
                    equipment.setEquipmentUserId(null);
                    equipment.setEquipmentFieldId(null);
                    equipment.setEquipmentNumber(null);
                    equipment.setEquipmentRemarks(null);
                    equipment.setEquipmentModelId(null);
                    equipment.setEquipmentPicture(null);
                    equipment.setEquipmentVideo(null);
                /*int i = riseService.deleteRiseByEquipmentId(eqId);
                int j = trailsService.deleteByEquipmentId(eqId);*/
                    Trails t = new Trails();
                    t.setTrailsEquipmentId(eqId);
                    List<Trails> trailsList = trailsService.selectByExample(t);
                    for(Trails trails:trailsList){
                        trails.setTrailsId(trails.getTrailsId());
                        trails.setTrailsGoodsStock(0);
                        trails.setTrailsGoodsId(null);
                        trailsService.updateByTrails(trails);
                    }
                    int result = equipmentService.updateByEqipment(equipment);

                    Field field = this.selectByFieldId(fieldId);
                    String beforeAddress = field.getFieldName() +"("+field.getFieldAddress()+") "+e.getEquipmentNumber()+"号机";
                    if(result != 0){
                        Transfer transfer = new Transfer();
                        transfer.setTransferEquipmentId(e.getEquipmentId());
                        transfer.setTransferBeforeAddress(beforeAddress);
                        transfer.setTransferUserId(e.getEquipmentUserId());
                        transfer.setTransferTime(ToolUtil.currentTime());
                        transfer.setTransferType("3");
                        transfer.setTransferFieldId(field.getFieldId());
                        transfer.setTransferEquipmentType(e.getEquipmentType());
                        transferService.insertSelective(transfer);
                    }
                    //删除线下订单表
                    //删除线上订单表
                }
            }
            return Msg.success();
        }catch(Exception e){
            return Msg.fail();
        }
    }


    /*
    *信号强度
    * */
    @ResponseBody
    @RequestMapping(value = "/getEquipmentSignal/{equipmentId}",method = RequestMethod.GET)
    @Authorization
    public Msg getEquipmentSignal(@PathVariable String equipmentId){
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        Equipment equipment = equipmentService.selectByPrimary(e);
        if(ToolUtil.isEmpty(equipment)){
            return Msg.fail().add("va_msg", "未找到对应的数据");
        }else {
            return Msg.success().add("equipment", equipment);
        }
    }

    /*
    * 修改备注
    * */
    @RequestMapping("/updateEquipmentByremarks")
    @ResponseBody
    @Authorization
    public Msg updateEquipmentByremarks(String equipmentId, String remarks){
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        e.setEquipmentRemarks(remarks);
        int result = equipmentService.updateByPrimaryKeySelective(e);
        if(result != 0){
            return Msg.success();
        }else{
            return Msg.fail().add("va_msg", "保存失败");
        }
    }
    /*
    *设备转移记录
    * */
    @RequestMapping("/getTransferByUser")
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg getTransferByUser(@CurrentUserId Integer userId, @CurrentAccountId Integer account,@CurrentFieldId Integer[] integers, String condition,
                                 @RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum){
        return transferService.getTransferByUser(userId,account,integers,condition,pageNum);
    }
    /***
     * 根据场地id查询场地下所有设备的收益情况
     * @param paramMap
     * @return
     */
    @RequestMapping("/getEquipmentListByFieldId")
    @ResponseBody
    @Authorization
    public Msg getEquipmentListByFieldId(@RequestBody Map<String, Object> paramMap){
        return equipmentService.getEquipmentListByFieldId(paramMap);
    }

    /**
     * 设置设备密码
     * @param equipmentId
     * @param equipmentPassword
     * @return
     */
    @ResponseBody
    @RequestMapping("/setEquipmentPassword")
    //@Authorization
    public Msg setEquipmentPassword(String equipmentId,String equipmentPassword){
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        equipment.setEquipmentPassword(MD5.string2MD5(equipmentPassword));
        int i = equipmentService.updateByPrimaryKeySelective(equipment);
        if(i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     *验证设备密码
     * @param equipmentId
     * @param equipmentPassword
     * @return
     */
    @RequestMapping("validateEquipmentPassword")
    @ResponseBody
    public Msg validateEquipmentPassword(String equipmentId,String equipmentPassword){
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        Equipment equipment = equipmentService.selectByPrimary(e);
        if(equipment.getEquipmentPassword().equals(MD5.string2MD5(equipmentPassword))){
            return Msg.success().add("va_msg", "密码正确");
        }else{
            return Msg.fail().add("va_msg", "密码错误");
        }
    }


    /**
     * 设备登录
     * @param equipmentId 设备id
     * @param equipmentPassword 设备密码
     * @return
     */
    @RequestMapping("/loginEquipment")
    @ResponseBody
    public Msg loginEquipment(String equipmentId,String equipmentPassword){
        if(ToolUtil.isEmpty(equipmentId)){
            return Msg.fail().add("msg","设备id不能为空");
        }else if(ToolUtil.isEmpty(equipmentPassword)){
            return Msg.fail().add("msg","密码不能为空");
        }
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        //e.setEquipmentPassword(equipmentPassword);
        Equipment equipment = equipmentService.selectByPrimary(e);
        if(ToolUtil.isEmpty(equipment)){
            return Msg.fail().add("msg","该设备不存在");
        }else if(ToolUtil.isEmpty(equipment.getEquipmentPassword())){
            return Msg.fail().add("msg","未设置密码");
        }else if(!equipment.getEquipmentPassword().equals(MD5.string2MD5(equipmentPassword))){
            return Msg.fail().add("msg","密码错误");
        }else{
            return Msg.success();
        }
    }

    /**
     * 删除设备
     * @param equipmentIds 设备id集合 用，隔开
     * @return
     */
    @RequestMapping(value = "/deleteEquipmentById/{equipmentIds}",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEquipmentById(@PathVariable("equipmentIds") String equipmentIds){
        if(equipmentIds.contains("-")){
            String[] strs = equipmentIds.split("-");
            for(int i = 0;i < strs.length;i++){
                equipmentService.deleteEquipmentById(strs[i]);
            }
        }else {
            equipmentService.deleteEquipmentById(equipmentIds);
        }
        return Msg.success();
    }

    /**
     * 根据id查询 Equipment
     *
     * @param
     * @return
     */
    public Equipment selectByEquipmentId(String EquipmentId) {
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(EquipmentId);
        Equipment equi = equipmentService.selectByPrimary(equipment);
        return equi;
    }

    /**
     * 根据id查询 Field
     *
     * @param FieldId
     * @return
     */
    public Field selectByFieldId(Integer FieldId) {
        Field field = new Field();
        field.setFieldId(FieldId);
        Field fifi = fieldService.selectByPrimary(field);
        return fifi;
    }
    /*
    * 字典表查询
    * */
    @RequestMapping(value = "/getDict",method = RequestMethod.GET)
    @ResponseBody
    public Msg getDict(Integer pid){
        List<Dict> list = equipmentService.selectDictByPid(pid);
        if(list.size()>0){
            return Msg.success().add("dict",list);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 查询设备的轮播图轮播视频
     * @param equipmentId
     * @return
     */
    @GetMapping("/selectEquipmentWheelMessage")
    @ResponseBody
    public Msg selectEquipmentWheelMessage(String equipmentId) {

        return this.equipmentService.selectEquipmentWheelMessage(equipmentId);
    }


    /**
     * 添加设备轮播图片
     * @param pictures
     * @return
     */
    @PostMapping("/updateEquipmentPicture")
    @ResponseBody
    public Msg updateEquipmentPicture(String equipmentId, String pictures) {

        return this.equipmentService.updateEquipmentPicture(equipmentId, pictures);
    }

    /**
     * 删除设备轮播图片
     * @param equipmentId
     * @param pictures
     * @return
     */
    @PostMapping("/deleteEquipmentPicture")
    @ResponseBody
    public Msg deleteEquipmentPicture(String equipmentId, String pictures) {

        return this.equipmentService.deleteEquipmentPicture(equipmentId, pictures);
    }


    /**
     * 停用设备
     * @param equipmentId
     * @return
     */
    @PostMapping("/discontinueEquipment")
    @ResponseBody
    public Msg discontinueEquipment(String equipmentId, String whetherUser) {

        return this.equipmentService.discontinueEquipment(equipmentId, whetherUser);
    }

    /**
     * 禁用启用设备（后台）
     * @param equipmentId 设备id
     * @param condition 使用情况(0.可用  1.禁用)
     * @return
     */
    @RequestMapping("/disabledEquipment")
    @ResponseBody
    public Msg disabledEquipment(@RequestParam String equipmentId,@RequestParam Integer condition){
        String type = null;
        String whetherUser = null;
        if(condition == 0){
            whetherUser = "usable";
            type = "可用";
        }else if (condition == 1){
            whetherUser = "unusable";
            type = "停用";
        }
        Equipment e = new Equipment();
        e.setEquipmentId(equipmentId);
        e.setEquipmentUseCondition(condition);
        int i = equipmentService.updateByPrimaryKeySelective(e);
        if(i > 0){
            //发送MQTT消息
            RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
            runnerSendMqtt.setMessage(equipmentId + "," + "0000" + "," + whetherUser);
            runnerSendMqtt.setRedisTemplate(redisTemplate);
            runnerSendMqtt.setTheme("SetUse");
            runnerSendMqtt.setThreadName("设备" + type);
            runnerSendMqtt.setRedisKey("Useable-" + equipmentId);
            runnerSendMqtt.start();
            return Msg.success();
        }
        return Msg.fail();
    }


    /**
     * 替换设备轮播图
     * @return
     */
    @PostMapping("/updateReplaceEquipmentPicture")
    @ResponseBody
    public Msg updateReplaceEquipmentPicture(String equipmentId) {

        return this.equipmentService.updateReplaceEquipmentPicture(equipmentId);
    }

    /**
     * 上传阿里云视频
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateEquipmentVideo")
    public Msg updateEquipmentVideo(String equipmentId, MultipartFile file){
        try{
            //AliyunOSSClientUtil.deleteVideo("http://shouhuojixiangmu.oss-cn-beijing.aliyuncs.com/20190212170738.MP4");
            String url = AliyunOSSClientUtil.getOSSUrl(file);

            //System.out.println("转码URL============="+url);
            if(ToolUtil.isEmpty(url)){
                return Msg.fail().add("msg","上传失败");
            }
            //转换工具路径
            String ffmpegPath = "E:/ffmpeg-4.1/ffmpeg-4.1";
            //boolean b = exchangeToMp4(ffmpegPath, url, codcFilePath);
            //String url = "http://shouhuojixiangmu.oss-cn-beijing.aliyuncs.com/video/20190214162235.MP4";
            Equipment e = new Equipment();
            e.setEquipmentId(equipmentId);
            //e.setEquipmentVideo(url);
            Equipment equipment = equipmentService.selectByPrimary(e);
            if(ToolUtil.isEmpty(equipment.getEquipmentVideo()) || equipment.getEquipmentVideo().equals("")){
                equipment.setEquipmentVideo(url);
            }else{
                equipment.setEquipmentVideo(equipment.getEquipmentVideo()+","+url);
            }
            int i = equipmentService.updateEquipmentVideo(equipment);
            if(i > 0){
                //发送MQTT消息
                String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(equipmentId + "," + fourNumber + ",change");
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("ChangeBanner");
                runnerSendMqtt.setThreadName("刷新广告指令");
                runnerSendMqtt.setRedisKey("ChangeBanner-" + equipmentId);
                runnerSendMqtt.start();

                return Msg.success().add("url",url);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return Msg.fail();
    }

    /**
     * 删除视频
     * @param url 视频url
     * @param equipmentId 设备id
     * @return
     */
    @RequestMapping("/deleteEquipmentVideo")
    @ResponseBody
    public Msg deleteEquipmentVideo(String url,String equipmentId){
        try{
            AliyunOSSClientUtil.deleteVideo(url);
            Equipment e = new Equipment();
            e.setEquipmentId(equipmentId);
            Equipment equipment = equipmentService.selectByPrimary(e);
            if(ToolUtil.isNotEmpty(equipment.getEquipmentVideo()) || !equipment.getEquipmentVideo().equals("")){
                if(equipment.getEquipmentVideo().contains(",")){
                    if(equipment.getEquipmentVideo().contains(url)){
                        System.out.println(equipment.getEquipmentVideo().indexOf(url+","));
                        if(equipment.getEquipmentVideo().indexOf(url+",") == -1){
                            //可能在最后
                            equipment.setEquipmentVideo(equipment.getEquipmentVideo().replace("," + url, ""));
                        }else{
                            //可能在中间,先去除中间的，才能去除最后的
                            equipment.setEquipmentVideo(equipment.getEquipmentVideo().replace(url + ",", ""));
                        }
                    }
                }else{
                    equipment.setEquipmentVideo(equipment.getEquipmentVideo().replace(url,""));
                }

            }
            //e.setEquipmentVideo(null);
            int i = equipmentService.updateEquipmentVideo(equipment);
            if(i > 0){
                //发送MQTT消息
                String fourNumber = ToolUtil.generateNonceStr(4);//随机数
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(equipmentId + "," + fourNumber + ",change");
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("ChangeBanner");
                runnerSendMqtt.setThreadName("刷新广告指令");
                runnerSendMqtt.setRedisKey("ChangeBanner-" + equipmentId);
                runnerSendMqtt.start();
                return Msg.success();
            }

        }catch(Exception e){
            return Msg.fail();
        }
        return Msg.fail();
    }


    /**
     * 设备货道测试
     * @param equipmentId    设备id
     * @param trailsId       货道id
     * @return
     */
    @RequestMapping("/equipmentTrailsTest")
    @ResponseBody
    public Msg equipmentTrailsTest (String equipmentId, @RequestParam(value = "trailsId", required = false)Integer trailsId, @RequestParam(value = "caseNumber", required = false)Integer caseNumber) {
        return this.equipmentService.equipmentTrailsTest(equipmentId, trailsId, caseNumber);
    }


    /**
     * 查询设备流量卡的信息(前台查询)
     * @param userId             用户id
     * @param equipmentId        设备id（传查当前设备的）
     * @param type               类型0查询最近七天   1查询当月的(默认查最近七天的)
     * @return
     */
    @RequestMapping("/selectEquipmentFlowcard")
    @ResponseBody
    @Authorization
    public Msg selectEquipmentFlowcard(@CurrentUserId Integer userId, String equipmentId, @RequestParam(value = "type", defaultValue = "0") Integer type) {
        return this.equipmentService.selectEquipmentFlowcard(userId, equipmentId, type);
    }


    /**
     * 查询物联卡的使用情况（后台查询）
     * @return
     */
    @RequestMapping("/selectFlowcardUseCondition")
    @ResponseBody
    public Msg selectFlowcardUseCondition() {
        return this.equipmentService.selctFlowcardUserCondition();
    }


    /**
     * Android保存截屏图片
     * @param file
     * @param equipmentId
     * @return
     */
    @RequestMapping("/uploadScreenshotPicture")
    @ResponseBody
    public Msg uploadScreenshotPicture(MultipartFile[] file, String equipmentId) {
        return this.equipmentService.uploadScreenshotPicture(file, equipmentId);
    }

    /**
     * 请求获取Android截屏图片
     * @param equipmentId
     * @param userId
     * @return
     */
    @RequestMapping("/requestScreenshotPicture")
    @ResponseBody
    @Authorization
    public Msg requestScreenshotPicture(String equipmentId, @CurrentUserId Integer userId) {
        return this.equipmentService.requestScreenshotPicture(equipmentId, userId);
    }


    /**
     * 调节设备音量
     * @param equipmentId       设备id
     * @param type              raise/lower
     * @return
     */
    @RequestMapping("/equipmentAdjustVolume")
    @ResponseBody
    public Msg equipmentAdjustVolume(String equipmentId, String type) {
        return this.equipmentService.equipmentAdjustVolume(equipmentId, type);
    }

    /**
     * 获取设备音量
     * @param equipmentId
     * @return
     */
    @RequestMapping("/selectEquipmentAudio")
    @ResponseBody
    public Msg selectEquipmentAudio(String equipmentId) {
        return this.equipmentService.selectEquipmentAudio(equipmentId);
    }

    /**
     * 上传拍照
     * @return
     */
    @RequestMapping("/uploadEquipmentCamera")
    @ResponseBody
    public Msg uploadPhoto(MultipartFile[] file, String equipmentId){
        return equipmentService.uploadPhoto(file,equipmentId);
    }


    /**
     * 请求拍照
     * @param equipmentId
     * @param userId
     * @return
     */
    @RequestMapping("/requestEquipmentCamera")
    @ResponseBody
    public Msg requestEquipmentCamera(String equipmentId, @CurrentUserId Integer userId){
        return equipmentService.requestEquipmentCamera(equipmentId,userId);
    }


    /**
     * 线下支付统计设备余币
     * @param equipmentId
     * @param coins
     * @return
     */
    @RequestMapping("/updateEquipmentCoin")
    @ResponseBody
    public Msg updateEquipmentCoin(String equipmentId, Integer coins) {
        return this.equipmentService.updateEquipmentCoin(equipmentId, coins);
    }


    /**
     * 修改设备总余币数
     * @param equipmentId
     * @param coins
     * @return
     */
    @RequestMapping("/updateEquipmentCoinCount")
    @ResponseBody
    public Msg updateEquipmentCoinCount(String equipmentId, Integer coins) {
        return this.equipmentService.updateEquipmentCoinCount(equipmentId, coins);
    }

}